package org.developer.websocketserver.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
@Slf4j
public class MessageServerHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof BinaryWebSocketFrame) {

            log.info("收到byte信息啦！");
            BinaryWebSocketFrame data = (BinaryWebSocketFrame) msg;
            ByteBuf byteBuf = data.content();
            log.info("msg长度大小={}",byteBuf.capacity());
            byte[] byteArray = new byte[byteBuf.capacity()];
            byteBuf.readBytes(byteArray);

        } else if (msg instanceof TextWebSocketFrame) {


            TextWebSocketFrame data = (TextWebSocketFrame) msg;
            log.info("收到消息啦={}", data.text());

            //获取当前 channel
            Channel currentChannel = ctx.channel();

//            //群发信息
//            ServerContext.channelGroup.stream().filter(channel -> channel != currentChannel).forEach(channel -> {
//                String sendMessage = String.format("[%s]\t %s\n", currentChannel.remoteAddress(), data.text());
//                channel.writeAndFlush(new TextWebSocketFrame(sendMessage));
//            });
        }

    }
}
